package com.icesoft.base.manager.config;

import com.icesoft.base.manager.config.resolver.AuthTokenUserArgumentResolver;
import com.icesoft.base.manager.config.resolver.ITokenUserService;
import com.icesoft.base.manager.config.resolver.LoginUserArgumentResolver;
import com.icesoft.base.manager.security.config.SecurityProperty;
import com.icesoft.core.Const;
import com.icesoft.core.web.helper.PathUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Component
@Slf4j
@AllArgsConstructor
public class ManagerMvcConfigurer implements WebMvcConfigurer {
    private final SecurityProperty securityProperty;
    private final Environment environment;
    private final ObjectProvider<ITokenUserService> tokenUserServiceObjectProvider;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String uploadPath = environment.getProperty("icesoft.upload.path", "");
        if (StringUtils.isNotBlank(uploadPath)) {
            log.info("自定义文件上传目录：{}", uploadPath);
            PathUtil.setUploadPath(uploadPath);
        }
        String preUrl = "/" + Const.preUploadPath + "/**";
        log.info("文件上传路径映射：{} -》 {}", preUrl, PathUtil.getRootUploadPath());
        registry.addResourceHandler(preUrl).addResourceLocations("file:///" + PathUtil.getRootUploadPath());
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new LoginUserArgumentResolver());
        resolvers.add(new AuthTokenUserArgumentResolver(tokenUserServiceObjectProvider.getIfAvailable()));
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        String[] urls = StringUtils.split(securityProperty.getCorsUrl(), ",");
        if (urls != null && urls.length > 0) {
            log.info("开启跨域访问：{}", securityProperty.getCorsUrl());
            registry.addMapping("/**").allowedOrigins(urls).allowedHeaders(urls)
                    .allowedMethods("POST", "GET", "OPTIONS", "DELETE", "PUT").allowCredentials(true)
                    .exposedHeaders(HttpHeaders.SET_COOKIE);
        }

    }
}
